package com.rp.system.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rp.system.user.entity.SysUserRole;
import com.rp.system.user.mapper.SysUserRoleMapper;
import com.rp.system.user.entity.SysUserRole;
import com.rp.system.user.service.SysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author vicente
 * @since 2020-12-02
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Override
    public Boolean insertOrDelete(List<String> SysUserRoleIdList, String userId) {

        Boolean boo = true;

        List<SysUserRole> list = super.list(new QueryWrapper<SysUserRole>().select("role_id").eq("user_id",userId));

        List<String> listOld = list.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());

        List<String> listNew = new ArrayList<>(SysUserRoleIdList);

        //需要增加的
        SysUserRoleIdList.removeAll(listOld);
        for(String string : SysUserRoleIdList){
            boo = super.save(new SysUserRole(userId,string));
            if(!boo){
                return false;
            }
        }

        //需要删除的
        listOld.removeAll(listNew);
        for(String string : listOld){
            boo = super.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId).eq("role_id", string));
            if(!boo){
                return false;
            }
        }
        return boo;
    }
}
